package Entry;

public class NumArray {
    int []nums;
    int start=0,end=0;
    int before=0;
    public NumArray(int[] nums) {
        this.nums=nums;
        if(nums.length<=0)return;
        before=nums[0];
    }

    public int sumRange(int i, int j) {
        if(j<start||i>end){
            start=i;end=j;
            before=0;
            for (int a=i;a<=j;a++){
                before+=nums[a];
            }
            return before;
        }
        if(i<start){
            for (int a=i;a<start;a++){
                before+=nums[a];
            }
            start=i;
        }else if(i>start){
            for (int a=start;a<i;a++){
                before-=nums[a];
            }
            start=i;
        }
        if(j<end){
            for (int b=j;b<end;b++){
                before-=nums[b+1];
            }
            end=j;
        }else if(j>end){
            for (int b=end;b<j;b++){
                before+=nums[b+1];
            }
            end=j;
        }
        return before;
    }
}
